'use strict';

const TOKEN_TTL = 60 * 60 * 24;

module.exports = function(server) {
  // Install a `/` route that returns server status
  var router = server.loopback.Router();

  router.get('/server-status', server.loopback.status());

  router.post('/login', function(req, res) {
    if (!req.body) return res.send('The API service exceptions has occured.');
    const userLoginInfo = {
      username: req.body.username,
      password: req.body.password,
      ttl: TOKEN_TTL
    };
    const SysUser = server.models.SysUser;
    SysUser.login(userLoginInfo, 'user', function(err, token) {
      if (err) {
        return res.status(401).send({
          userName: userLoginInfo.username,
          permissionFailed: true,
          msg: 'authentication failed, you do not have permission!'
        });
      }
      token = token.toJSON();
      res.send({
        userId: token.userId,
        userName: token.user.username,
        userEmail: token.user.email,
        token: token.id
      });
    });
  });

  router.post('/logout', function(req, res) {
    if (!req.body || !req.body) return res.send('The API service exceptions has occured.');
    let token = req.body.token || req.query['token'];
    const SysUser = server.models.SysUser;
    SysUser.logout(token, function(err) {
      if (err)
        return res.status(401).send({
          logoutFailed: true,
          message: err
        });
      else
        return res.send();
    });
  });

  // router.get('/', server.loopback.status());
  server.use(router);
};
